import React  from 'react';
import {message,Icon,Button,Input,Row,Col,Card,Anchor,Table,Dropdown,Menu,Form,DatePicker,InputNumber,Upload} from 'antd';
import styles from '../style/PropertyDataDetailInfo.scss';
const { RangePicker } = DatePicker;
import moment from 'moment';
import api from 'container/api';
import {
  ASSET_LEVEL,
  IS_NOT,
  GUARANTEE,
  TRANSPORT_TYPE,
  RETURNED_MONEY_WAY,
  RETURNED_MONEY_SOURCE,
  REMARK_TYPE
} from 'constants/index';
//货权信息
class PropertyOwnership extends React.Component {

  constructor(props){
    super(props)
    let {id} = props;
    this.state ={
      id,
      data:{},
      isEdit:false
    }
  }

  componentWillMount(){
    this.doFetch();
  }

  async doFetch(){
    let {id} = this.state;
    let result  = await api ('/assets/property-ownership-detail' ,{id});
    if(!result.success){
      message.error(result.message);
      return
    }
    let data = result.data;

    Object.keys(data).forEach((key,index) => {
      if(key.endsWith('files') && Array.isArray(data[key])){
        data[key].forEach((item,index) => {
          item.uid = this.uuid();
        })
      }
    })
    this.setState({data:result.data,isEdit:false});
  }
  
  toggleEdit (isEdit){
    let {data} = this.state;
    this.setState({isEdit})
  }

  handleSave = () => {
    this.props.form.validateFields((err, values) => {
      if (err) return;
      this.save({...values})
    });
  }

  async save (values) {
    let deliveryDate = values.delivery_date;
    values.delivery_start_date =deliveryDate[0]?deliveryDate[0].format('YYYY-MM-DD'):null;
    values.delivery_end_date = deliveryDate[1]?deliveryDate[1].format('YYYY-MM-DD'):null;
    values.transfer_date = values.transfer_date?values.transfer_date.format('YYYY-MM-DD'):null;
    values.test_date = values.test_date?values.test_date.format('YYYY-MM-DD'):null;
    delete values.delivery_date;
    values.asset_id = this.state.id;
    values.id = this.state.data.id;

    let result = await api("/assets/PropertyOwnership/edit",values);
    if(!result.success){
      message.error(result.message);
      return
    }
    message.success("更新货权信息成功" , 1 ,() => {
      this.doFetch();
    })
  }

  uuid(){
    return Math.random().toString(36).slice(2);
  }


  render(){
    let {data,isEdit} = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <Card 
        title="货权信息" 
        bordered={false} 
        bodyStyle={{backgroundColor:'#fff',padding:'0'}}
        extra={
          this.renderTd(
            <div>
              <Button style={{marginRight:5}} onClick={this.toggleEdit.bind(this,false)}>取消</Button>
              <Button type='primary' onClick={this.handleSave}>保存</Button>
            </div>,
            <a href='javascript:void 0' onClick={this.toggleEdit.bind(this,true)}>
            <Icon type="edit" />
            </a>
          )
        }
      >
      <Form>
        <table className={styles.table}>
          <tbody className='table-form'>
            <tr>
              <th>发货日期</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('delivery_date', {
                      rules: [{ type: 'array',required: true, message: '请选择发货日期' }],
                      initialValue:[
                        data.delivery_start_date?moment(data.delivery_start_date):null,
                        data.delivery_end_date?moment(data.delivery_end_date):null
                      ]
                    })(
                      <RangePicker />
                    )}
                  </Form.Item>,
                  `${data.delivery_start_date} 至 ${data.delivery_end_date}`
                )}
              </td>
              <th>货权转移日期</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('transfer_date', {
                      rules: [{required: true, message: '请选择货权转移日期' }],
                      initialValue:data.transfer_date?moment(data.transfer_date):null
                    })(
                      <DatePicker />
                    )}
                  </Form.Item>,
                  data.transfer_date
                )}
              </td>
            </tr>
            <tr>
              <th>货物吨数</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('amount', {
                      rules: [{required: true, message: '请输入货物吨数' }],
                      initialValue:data.amount
                    })(
                      <Input addonAfter='吨' />
                    )}
                  </Form.Item>,
                  `${data.amount}吨`
                )}
              </td>
              <th>货物单价</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('unit_price', {
                      rules: [{required: true, message: '请输入货物单价' }],
                      initialValue:data.unit_price
                    })(
                      <Input placeholder='请输入货物单价' addonAfter='元/吨' />
                    )}
                  </Form.Item>,
                  `${data.unit_price}元/吨`
                )}
              </td>
            </tr>
            <tr>
              <th>货物金额</th>
              <td>
                {data.total_price}元
              </td>
              <th>货物用途</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('usage', {
                      rules: [{required: true, message: '请输入货物用途' }],
                      initialValue:data.usage
                    })(
                      <Input placeholder='请输入货物用途' />
                    )}
                  </Form.Item>,
                  `${data.usage}`
                )}
              </td>
            </tr>
            <tr>
              <th>化验日期</th>
              <td colSpan={3}>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('test_date', {
                      rules: [{required: true, message: '请选择化验日期' }],
                      initialValue:data.test_date?moment(data.test_date):null
                    })(
                      <DatePicker />
                    )}
                  </Form.Item>,
                  `${data.test_date}`
                )}
              </td>
            </tr>
            <tr>
              <th>货物照片</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('property_files', {
                    rules: [{ required: true, message: '请上传货物照片' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.property_files
                  })(
                    <Upload {...this.uploadProps(16,'property_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>

              </td>
            </tr>
            <tr>
              <th>运输工具照片</th>
              <td colSpan={3}>
                  <Form.Item>
                    {getFieldDecorator('tool_files', {
                      rules: [{ required: true, message: '请上传运输工具照片' }],
                      valuePropName: 'fileList',
                      getValueFromEvent: this.normFile,
                      initialValue:data.tool_files
                    })(
                      <Upload {...this.uploadProps(17,'tool_files')}>
                        {!isEdit?null
                          :<Button>
                            <Icon type="upload" /> 点击上传
                          </Button>
                        } 
                      </Upload>
                    )}
                  </Form.Item>
              </td>
            </tr>
            <tr>
              <th>运输照片</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('transport_files', {
                    rules: [{ required: false, message: '请上传运输照片' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.transport_files
                  })(
                    <Upload {...this.uploadProps(18,'transport_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>过衡单</th>
              <td colSpan={3}>
                  <Form.Item>
                    {getFieldDecorator('sheet_files', {
                      rules: [{ required: false, message: '请上传过衡单' }],
                      valuePropName: 'fileList',
                      getValueFromEvent: this.normFile,
                      initialValue:data.sheet_files
                    })(
                      <Upload {...this.uploadProps(19,'sheet_files')}>
                        {!isEdit?null
                          :<Button>
                            <Icon type="upload" /> 点击上传
                          </Button>
                        } 
                      </Upload>
                    )}
                  </Form.Item>
              </td>
            </tr>
            <tr>
              <th>化验单</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('laboratory_files', {
                    rules: [{ required: false, message: '请上传化验单' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.laboratory_files
                  })(
                    <Upload {...this.uploadProps(20,'laboratory_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>货权转移证明</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('cert_files', {
                    rules: [{ required: false, message: '请上传货权转移证明' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.cert_files
                  })(
                    <Upload {...this.uploadProps(21,'cert_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
          </tbody>
        </table>
      </Form>
      </Card>
    )
  }

  uploadProps = (file_type,field) => {
    let _this = this;
    let {data} = this.state;
    data[field] = data[field] || [];
    return {
      customRequest:async ({ file, fileList }) => {
        let {defaultFileList=[]} = this.state;
        let result = await api.upload(`/file/upload?file_type=${file_type}`,file);
        if(result){
          let uid = this.uuid();
          data[field].push({
            name:file.name,
            url:result.data.url,
            type:result.data.type,
            uid:uid,
            status:'done'
          })
        }
        this.props.form.setFieldsValue({
          [field]:data[field]
        })
        this.setState({data})
      },
      onRemove:(file) => {
        let {isEdit} = _this.state;
        return isEdit
      }
    }
  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  renderTd (editHtml,html) {
    let {isEdit} = this.state;
    if(isEdit) return editHtml;
    return html;
  }
}
export default Form.create()(PropertyOwnership);
